<template>
  <Category :scene="scene" />
  <el-card style="margin: 10px 10px;">
    <div :v-show="scene == 0">
      <el-button :disabled="!categoryStore.category3Id" type="primary" icon="Plus" @click="addSpu">添加SPU</el-button>
      <el-table :data="spuList" stripe border style="width: 100%;margin-top: 10px;">
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column label="SPU名称" prop="spuName" />
        <el-table-column label="SPU描述" prop="description" :show-overflow-tooltip="true" />
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <!-- 添加sku -->
            <el-button type="primary" icon="Plus" size="mini" title="添加SKU" @click="addSku(row)"></el-button>
            <el-button type="primary" icon="Edit" size="mini" title="修改SPU" @click="updateSpu(row)"></el-button>
            <el-button type="primary" icon="View" size="mini" title="查看SKU" @click="findSkuBySpuId(row)"></el-button>
            <el-popconfirm class="box-item" :title="`确定删除${row.spuName}吗`" placement="top-start"
              @confirm="handlerDelete(row, $index)">
              <template #reference>
                <el-button type="danger" icon="Delete" size="mini" title="删除spu"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加分页器 -->
      <el-pagination v-model:current-page="pageIndex" v-model:page-size="pageSize" :page-sizes="[2, 3, 5, 7]"
        :small="true" :background="true" layout=" prev, pager, next, jumper ,  ->, sizes, total" :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <!-- 绑定一个自定义事件 更改 scene 的变量值 -->
    <SpuForm :v-show="scene == 1" @changeScene="changeScene" ref="supFormRef" />
    <SkuForm :v-show="scene == 2" @changeScene="changeScene" ref="skuFormRef" />
    <!-- dialog 对话框：展示已有的sku数据 -->
    <el-dialog title="SKU列表" v-model="show">
      <el-table :data="skuArr" border>
        <el-table-column label="sku名字" prop="spuName" />
        <el-table-column label="sku价格" prop="price" />
        <el-table-column label="sku重量" prop="weight" />
        <el-table-column label="sku图片">
          <template #default="{ row }">
            <img :src="row.skuDefaultImg" alt="" style="width: 100px;height: 100px;">
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">

import { onBeforeUnmount, ref, watch } from 'vue'
import { reqDeleteSpu, reqSpuList, reqSpuSkuList, } from '@/api/product/spu'
import type { PageInstanceVO, Response } from '@/api/type';
import type { SpuList, SpuVO } from '@/api/product/spu/type';
//  引入分类的小仓库
import { useCategoryStore } from '@/store/modules/category';
import { ElMessage } from 'element-plus';
import SpuForm from './SpuForm.vue';
import SkuForm from './SkuForm.vue';
import { SkuList } from '@/api/product/sku/type';
const categoryStore = useCategoryStore();
let spuList = ref<SpuList>([]);
let scene = ref<number>(0); // 0 列表，1：添加或编辑spu 2:编辑sku
let pageIndex = ref<number>(1);
let pageSize = ref<number>(3);
let total = ref<number>(0);
let supFormRef = ref<any>();

let skuFormRef = ref<any>();
// 存储全部的sku数据
let skuArr = ref<SkuList>([]);

let show = ref<boolean>(false);







// 根据spuId查询sku列表
const findSkuBySpuId = async (row: SpuVO) => {
  // 跳转到sku页面
  let skuListResult = await reqSpuSkuList(row.id as number);
  if (skuListResult.code === 200) {
    skuArr.value = skuListResult.data || [];
    show.value = true; // 显示dialog对话框
  } else {
    ElMessage.error(skuListResult.message);
  }

}

// 添加spu方法

const addSpu = (row: SpuVO) => {
  scene.value = 1;
  // 使用子组件的 实例 ，并调用子组件的addSpu方法
  supFormRef.value.initAddSpu(row, pageIndex.value);
}


// 更新
const updateSpu = (row: SpuVO) => {
  scene.value = 1;
  supFormRef.value.initHashSpuData(row, pageIndex.value)
}
// 子组件的自定义事件：有子组件调用：目的是更改场景值
const changeScene = (obj: any) => {
  // 子组件改变场景
  scene.value = obj.flag;
  if (obj.params == 'update') {
    //更新留在当前页
    getSpuList(pageIndex.value);
  } else if (obj.params == 'add') {
    // 添加跳转到第一页
    getSpuList();
  }
}

const addSku = (row: SpuVO) => {
  // 
  scene.value = 2;
  // 通过skuFormRef调用其对外暴露的接口
  skuFormRef.value.initSkuData(categoryStore.category1Id, categoryStore.category2Id, row)


}
const handleSizeChange = async (limit: number) => {
  pageSize.value = limit;
  pageIndex.value = 1;
  getSpuList();

}

const handleCurrentChange = async (pageNo: number) => {
  pageIndex.value = pageNo;
  getSpuList(pageNo);
}
const getSpuList = async (pageIndex: number = 1) => {
  let category3Id = categoryStore.category3Id as number;
  console.log('category3Id:', category3Id)
  let result: Response<PageInstanceVO<SpuVO>> = await reqSpuList(pageIndex, pageSize.value, category3Id);
  console.log('result:', result);
  if (result.code === 200) {
    let pi = result.data;
    spuList.value = pi?.list || [];
    total.value = pi?.total || 0;
  }
}



const handlerDelete = async (row: SpuVO, index: number) => {
  console.log('row:', row);
  console.log('index:', index);
  let result: Response<void> = await reqDeleteSpu(row.id as number)
  if (result.code === 200) {
    ElMessage.success('删除成功');
    await getSpuList(spuList.value.length > 1 ? pageIndex.value : pageIndex.value - 1);
    return
  }
  ElMessage.error(result.message);
}


watch(() => categoryStore.category3Id, () => {
  // 如果没有选择三级分类，那么spuList清空
  if (!categoryStore.category3Id) {
    spuList.value = [];
    return;
  }
  getSpuList();

})
// 每次路由销毁的时候清空仓库信息
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style scoped lang="scss"></style>